package com.pitop.base.ctrl;

import com.alibaba.fastjson.JSONObject;
import com.pitop.core.entity.BeanRet;
import com.pitop.core.tools.ConfigUtil;
import com.pitop.core.tools.FileUpTools;
import com.pitop.core.tools.redis.RedisUtils;
import com.pitop.setting.entity.Setting;
import com.pitop.setting.service.SettingSVImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

/**
 * 上传图片
 *
 * @author pi-top
 */
@RestController
@RequestMapping("/upload")
@Slf4j
@Api(value = "账户控制器", description = "账户控制器")
public class UploadCtrl {

    private final static Logger logger = LoggerFactory.getLogger(UploadCtrl.class);

    @Autowired
    private SettingSVImpl settingSVImpl;

    @Resource
    protected RedisUtils redisUtils;

    @ApiOperation(value = "上传图片--用于富文本中", notes = "上传图片--用于富文本中")
    @PostMapping("/uploadToEditor")
    @ResponseBody
    public void uploadToEditor(HttpServletRequest request, HttpServletResponse response, @ApiParam(value = "springmvc文件对象", required = true) @RequestParam MultipartFile upload) {
        boolean result = false;
        FileUpTools fileUpTools = new FileUpTools();
        String path = ConfigUtil.getValue("upload_temp_dir", "upload_config.properties");
        String suffix = ConfigUtil.getValue("suffix_img", "upload_config.properties");
        String domain = ConfigUtil.getValue("service_domain", "upload_config.properties");
        String fileName = System.currentTimeMillis() + suffix;
        try {
            InputStream inputStream = upload.getInputStream();
            fileUpTools.uploadFileToLocal(inputStream, path, fileName);
            result = true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            response.setContentType("text/html;charset=UTF-8");
            String callback = request.getParameter("CKEditorFuncNum");
            PrintWriter out = response.getWriter();
            if (result) {
                out.println("<script type=\"text/javascript\">");
                out.println("window.parent.CKEDITOR.tools.callFunction(" + callback + ",'" + domain + "/" + fileName + "',''" + ")");
                out.println("</script>");
            } else {
                out.println("<script type=\"text/javascript\">");
                out.println("window.parent.CKEDITOR.tools.callFunction(" + callback + ",''," + "'上传失败');");
                out.println("</script>");
            }
            out.flush();
            out.close();
        } catch (Exception e) {
            logger.info("<< 上传失败，原因是:" + e.getMessage());
        }
    }


    @ApiOperation(value = "上传图片", notes = "上传图片")
    @PostMapping("/upload")
    @ResponseBody
    public BeanRet upload(@ApiParam(value = "springmvc文件对象", required = true) @RequestParam MultipartFile upload) {
        FileUpTools fileUpTools = new FileUpTools();
        Setting setting = settingSVImpl.loadByK(Setting.Key.Upload_Url.name());
        String path = setting.getV();
        setting = settingSVImpl.loadByK(Setting.Key.Upload_Service_Domain.name());
        String domain = setting.getV();
        String originalFileName = upload.getOriginalFilename();
        String fileType = originalFileName.substring(originalFileName.lastIndexOf('.'));
//        String suffix = ConfigUtil.getValue("suffix_img", "upload_config.properties");
        String fileName = System.currentTimeMillis() + fileType;
        try {
            InputStream inputStream = upload.getInputStream();
            fileUpTools.uploadFileToLocal(inputStream, path, fileName);
        } catch (IOException e) {
            e.printStackTrace();
            return BeanRet.create(false, "图片上传失败", null);
        }
        String url;
        url = domain + "/" + fileName;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("url", url);
        return BeanRet.create(true, "图片上传成功", jsonObject);
    }


}
